package net.discard.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**
 * Created by Baowen on 2017/2/23.
 */
public class Base64Utils {

    private static final Logger logger = LoggerFactory.getLogger(Base64Utils.class);

    /**
     * byte -> String
     */
    public static String encode(byte[] bytes) {
        return new BASE64Encoder().encode(bytes);
    }

    public static byte[] decode(String str) {
        try {
            return new BASE64Decoder().decodeBuffer(str);
        } catch (IOException e) {
            logger.error("base64异常。", e);
        }
        return null;
    }

    /**
     * base64 解码。
     *
     * @param base64
     * @return
     */
    @Deprecated
    public static byte[] base64ToByte(String base64) {
        byte[] bytes = new byte[0];
        if (StringUtils.isEmpty(base64)) {
            return bytes;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            bytes = decoder.decodeBuffer(base64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
        } catch (Exception e) {
            logger.error("base64解码异常", e);
            throw new RuntimeException("base64解码异常");
        }
        return bytes;
    }

}
